import React, { Fragment } from 'react';
import { inject, observer } from 'mobx-react';
import { Row, Button } from 'antd';
import { WeaEchart, WeaLocaleProvider, WeaReportCard, WeaAlertPage, WeaDialog, WeaMoreButton } from 'ecCom';
import { toJS } from 'mobx';
import ReportFlowEchartDetailListDialogComponent from './ReportFlowEchartDetailListDialogComponent';
import ReportFlowDetailListDialogComponent from './ReportFlowDetailListDialogComponent';
import ReportDocDetailListDialogComponent from './ReportDocDetailListDialogComponent';
import ReportDocEchartDetailListDialogComponent from './ReportDocEchartDetailListDialogComponent';

const getLabel = WeaLocaleProvider.getLabel;

@inject('reportStore')
@inject('reportFlowDetailListDialogStore')
@inject('reportFlowEchartDetailListDialogStore')
@inject('reportDocDetailListDialogStore')
@inject('reportDocEchartDetailListDialogStore')

// query 参数详解 : propose 拟办 post 发文 receive 收文  sign 签报

@observer
class FlowChartComponent extends React.Component {
  constructor(props) {
    super(props);
    if (props.params && props.params.id) {
      const title = this.getEcharTitle(props.params.id);
      this.state = {
        option2: {
          id: this.type,
          tooltip: {},
          legend: {},
          grid: {
            left: '3%',
            right: '1%',
            bottom: '3%',
            containLabel: true,
          },
          xAxis: {},
          yAxis: {},
          series: [],
        },
        title,
        hasData: false,
      };
    } else {
      this.state = {
        option2: {
          id: this.props.id || this.props.echart.id,
          tooltip: this.props.echart.tooltip,
          legend: this.props.echart.legend,
          grid: {
            left: '3%',
            right: '1%',
            bottom: '3%',
            containLabel: true,
          },
          xAxis: this.props.echart.xAxis,
          yAxis: this.props.echart.yAxis,
          series: this.props.echart.series,
        },
        title: this.props.title,
        hasData: false,
      };
    }
    this.downImage = this.downImage.bind(this);
  }

  componentDidMount() {
    if (!this.props.echart) {
      const { reportStore } = this.props;
      const { doSearch } = reportStore;
      switch (this.props.params.id) {
        case 'propose':
          doSearch({ dateType: 0, orgtype: 1, officaltype: '' });
          break;
        case 'post':
          doSearch({ dateType: 0, orgtype: 1, officaltype: '1' });
          break;
        case 'receive':
          doSearch({ dateType: 0, orgtype: 1, officaltype: '2' });
          break;
        case 'sign':
          doSearch({ dateType: 0, orgtype: 1, officaltype: '3' });
          break;
      }
    }
  }

  componentWillReceiveProps(nextProps) {
    let { option2 } = this.state;
    if (this.props.echart !== nextProps.echart) {
      option2.legend = nextProps.echart.legend;
      option2.xAxis = nextProps.echart.xAxis;
      option2.yAxis = nextProps.echart.yAxis;
      option2.series = nextProps.echart.series;
      option2.tooltip = nextProps.echart.tooltip;
    }
    this.setState({ option2, hasData: false });
    if (option2.series) {
      option2.series.forEach((item) => {
        item.data.forEach((i) => {
          if (Number.parseInt(i) > 0) {
            this.setState({ hasData: true });
          }
        });
      });
    }

    if (this.refs.chart) {
      this.refs.chart.paint();
    }
    if (this.props.title !== nextProps.title) {
      this.setState({ title: nextProps.title });
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (nextState.title !== this.state.title || nextState.hasData !== this.state.hasData) {
      return true;
    }
  }

  render() {
    const { option2, title, hasData } = this.state;
    const { reportFlowEchartDetailListDialogStore, reportStore, reportFlowDetailListDialogStore, params, echart,
      reportDocDetailListDialogStore, reportDocEchartDetailListDialogStore } = this.props;
    const { echart1, echart2, searchParamsFlow, searchParamsDoc } = reportStore;
    let option = option2;
    const inPortal = this.props.params && this.props.params.id;
    if (!echart) {
      this.getSingleReport();
      option = {
        id: params.id == 'propose' ? 'flowchart1' : 'flowchart2',
        tooltip: params.id == 'propose' ? toJS(echart1.tooltip) : toJS(echart2.tooltip),
        legend: params.id == 'propose' ? toJS(echart1.legend) : toJS(echart2.legend),
        grid: {
          left: '3%',
          right: '1%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: params.id == 'propose' ? echart1.xAxis : echart2.xAxis,
        yAxis: params.id == 'propose' ? echart1.yAxis : echart2.yAxis,
        series: params.id == 'propose' ? toJS(echart1.series) : toJS(echart2.series),
      };
    }
    const isIE = window.navigator.appVersion.includes('Trident');
    const flowEchartDetailListDialogButtons = [
      // <Button type="primary" onClick={() => reportFlowEchartDetailListDialogStore.tableStore.exportAll()} >{getLabel('28343', "导出Excel")}</Button>,
      <WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@mljesx@more`} collectParams={{ favname: '', favouritetype: 2, objid: 0, importantlevel: 1 }} />,
    ];
    const flowDetailListDialogButtons = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@lpjmbk@export`} type="primary" onClick={() => reportFlowDetailListDialogStore.tableStore.exportAll()} >{getLabel('28343', '导出Excel')}</Button>,
      <WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@3hutsh@more`} collectParams={{ favname: '', favouritetype: 2, objid: 0, importantlevel: 1 }} />,
    ];
    const docDetailListDialogButtons = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@v5bu8c@export`} type="primary" onClick={() => reportDocDetailListDialogStore.tableStore.exportAll()} >{getLabel('28343', '导出Excel')}</Button>,
      <WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@vpa76j@more`} collectParams={{ favname: '', favouritetype: 2, objid: 0, importantlevel: 1 }} />,
    ];
    const docEchartDetailListDialogButtons = [
      // <Button type="primary" onClick={() => reportDocEchartDetailListDialogStore.tableStore.exportAll()} >{getLabel('28343', "导出Excel")}</Button>,
      <WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@dxvpvz@more`} collectParams={{ favname: '', favouritetype: 2, objid: 0, importantlevel: 1 }} />,
    ];

    let weaReportCardClass = '';
    if (params && params.id && params.id != 'propose') {
      weaReportCardClass = 'col_flowchart2';
    }
    return (
      <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@2xjecz`} className={'odoc-reportchart'}>
        {
          hasData &&
          <WeaReportCard ecId={`${this && this.props && this.props.ecId || ''}_WeaReportCard@ox8uqe`}
            title={title}
            // onMoreClick={v => this.showMoreDialog() }
            // onDownloadClick={v => this.downImage() }
            className={`report-card ${weaReportCardClass}`}
            operations={
              <div>
                <span onClick={this.showMoreDialog} className="cursor-pointer more" style={{ paddingRight: '10px' }}>{getLabel('17499', '更多')}</span>
                {!isIE && <span className="icon-coms-download2 cursor-pointer more" onClick={() => this.downImage()} />}
              </div>
            }
          >

            <WeaEchart ecId={`${this && this.props && this.props.ecId || ''}_WeaEchart@toy993`} ref={'chart'} chartName={''} option={option} chartAction={chart => this.chartAction(chart)} />
          </WeaReportCard>
        }
        {
          !hasData &&
          <div className="report-row echart-nodata">
            <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@3ykmxk`} icon="icon-coms-blank" >
              <div style={{ color: '#000' }}>
                {getLabel(83553, '暂无数据')}
              </div>
            </WeaAlertPage>
          </div>
        }

        {
          inPortal &&
          <Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@o90k18`}>
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@iiwolh`}
              title={getLabel('383719', '公文流程拟办排名')}
              icon={'icon-coms-official'}
              iconBgcolor={'#f14a2d'}
              visible={reportFlowEchartDetailListDialogStore.visable}
              style={{ width: 950, height: 700 }}
              hasScroll
              onCancel={reportFlowEchartDetailListDialogStore.hideDialog}
              buttons={flowEchartDetailListDialogButtons}
            >
              <ReportFlowEchartDetailListDialogComponent
                ecId={`${this && this.props && this.props.ecId || ''}_ReportFlowEchartDetailListDialogComponent@twsayw`}
                searchParams={toJS(searchParamsFlow)}
                name={reportFlowEchartDetailListDialogStore.condition_name}
              />
            </WeaDialog>

            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@ek47ye`}
              title={getLabel('383302', '具体流程清单')}
              icon={'icon-coms-official'}
              iconBgcolor={'#f14a2d'}
              visible={reportFlowDetailListDialogStore.visable}
              hasScroll
              style={{ width: 950, height: 700 }}
              onCancel={reportFlowDetailListDialogStore.hideDialog}
              buttons={flowDetailListDialogButtons}
            >
              <ReportFlowDetailListDialogComponent ecId={`${this && this.props && this.props.ecId || ''}_ReportFlowDetailListDialogComponent@ez1ud4`}
                searchParams={toJS(searchParamsFlow)}
                status={reportFlowDetailListDialogStore.condition_status}
                key={reportFlowDetailListDialogStore.condition_key}
              />
            </WeaDialog>

            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@3qcccc`}
              title={getLabel('383855', '具体公文清单')}
              icon={'icon-coms-official'}
              iconBgcolor={'#f14a2d'}
              visible={reportDocDetailListDialogStore.visable}
              style={{ width: 950, height: 700 }}
              hasScroll
              onCancel={reportDocDetailListDialogStore.hideDialog}
              buttons={docDetailListDialogButtons}
            >
              <ReportDocDetailListDialogComponent
                ecId={`${this && this.props && this.props.ecId || ''}_ReportDocDetailListDialogComponent@27atlg`}
                searchParams={toJS(searchParamsDoc)}
                status={reportDocDetailListDialogStore.condition_status}
                key={reportDocDetailListDialogStore.condition_key}
              />
            </WeaDialog>

            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@fllm7t`}
              title={reportDocEchartDetailListDialogStore.getDialogTitleName()}
              icon={'icon-coms-official'}
              iconBgcolor={'#f14a2d'}
              visible={reportDocEchartDetailListDialogStore.visable}
              style={{ width: 950, height: 700 }}
              hasScroll
              onCancel={reportDocEchartDetailListDialogStore.hideDialog}
              buttons={docEchartDetailListDialogButtons}
            >
              <ReportDocEchartDetailListDialogComponent
                ecId={`${this && this.props && this.props.ecId || ''}_ReportDocEchartDetailListDialogComponent@qusv9y`}
                searchParams={toJS(searchParamsDoc)}
                name={reportDocEchartDetailListDialogStore.condition_name}
                analyseType={reportDocEchartDetailListDialogStore.condition_analyseType}
              />
            </WeaDialog>

          </Fragment>
        }


      </Row>);
  }

  chartAction(chart) {
    const { reportFlowDetailListDialogStore, reportDocDetailListDialogStore } = this.props;
    chart.off('click');
    chart.on('click', (params) => {
      let option = chart.getModel().option;
      let chartid = option.id;
      if (chartid == 'flowchart1') {
        let status = option.series[params.seriesIndex].status;
        let dataKey = option.series[params.seriesIndex].dataKey[params.dataIndex];
        reportFlowDetailListDialogStore.showDialog(status, dataKey);
      }
      if (chartid == 'flowchart2') {
        let status = '0';
        let dataKey = option.series[params.seriesIndex].dataKey[params.dataIndex];
        reportFlowDetailListDialogStore.showDialog(status, dataKey);
      }
      if (chartid == 'docchart1' || chartid == 'docchart2' || chartid == 'docchart3' || chartid == 'docchart4' || chartid == 'docchart5') {
        let dataKey = option.series[params.seriesIndex].dataKey[params.dataIndex];
        reportDocDetailListDialogStore.showDialog(dataKey);
      }
    });
  }

  showMoreDialog = () => {
    const { reportFlowEchartDetailListDialogStore, reportDocEchartDetailListDialogStore } = this.props;
    if (this.state.option2.id == 'flowchart1') {
      reportFlowEchartDetailListDialogStore.showDialog();
    } else if (this.state.option2.id == 'docchart1') {
      reportDocEchartDetailListDialogStore.showDialog(1);
    } else if (this.state.option2.id == 'docchart2') {
      reportDocEchartDetailListDialogStore.showDialog(2);
    } else if (this.state.option2.id == 'docchart4') {
      reportDocEchartDetailListDialogStore.showDialog(4);
    } else if (this.state.option2.id == 'docchart5') {
      reportDocEchartDetailListDialogStore.showDialog(5);
    }
  }

  // ie下会出现下载不了图片  pixelRatio 减小分辨率  图片模糊
  downImage() {
    let aTag = document.createElement('a');
    aTag.href = this.refs.chart.chart.getDataURL({ type: 'PNG', pixelRatio: 1 });
    aTag.download = 'download.PNG';
    document.body.appendChild(aTag);
    aTag.click();
    document.body.removeChild(aTag);
  }

  getSingleReport() {
    const { echart1 } = this.props.reportStore;
    echart1.series && toJS(echart1.series).forEach((item) => {
      item.data.forEach((i) => {
        if (Number.parseInt(i) > 0) {
          this.setState({ hasData: true });
        }
      });
    });
  }

  getEcharTitle(id) {
    let title = `${getLabel('383719', '公文流程拟办排名')}（Top5）`;
    this.type = 'flowchart1';
    if (id == 'post') {
      title = getLabel('383721', '发文环节统计');
      this.type = 'flowchart2';
    } else if (id == 'receive') {
      title = getLabel('510617', '收文环节统计');
      this.type = 'flowchart2';
    } else if (id == 'sign') {
      title = getLabel('510618', '签报环节统计');
      this.type = 'flowchart2';
    }
    return title;
  }
}

export default FlowChartComponent;
